import { useEffect, useState, useRef } from 'react';
import { message, Slider, Tooltip } from 'antd';
import { ModalForm, ProFormDigit, ProFormRadio, ProFormCheckbox } from '@ant-design/pro-components';
import styles from './index.module.less';
import {
  chengFa,
  chuFa,
  isLocal,
  isSuccess,
  jingDuNum,
  localUserInfo,
  orderText,
  zhiYingSunTriggerPrice,
} from '@/utils';
import { priceTypeOptions, weiTuoOptions } from '@/utils/helper';
import { feiLvApi, zhiYingSunApi } from '@/api';
import { Desc } from './ZhiYingSunCpn';
import ZhiYingBFList from './ZhiYingBFList';
import { ShouYiLvSlider } from './CommonCpn';

export default function ZhiYingBuFenModal({ open, setOpen, formData, reload, contractList }: any) {
  const shouYiLv = isLocal() ? 0 : 0;
  const formRef: any = useRef('');
  const [showZhiYing, setShowZhiYing] = useState(false);
  const [showZhiSun, setShowZhiSun] = useState(false);
  const [showBFList, setShowBFList] = useState(false);
  const [yingDisabled, setYingDisabled] = useState(false);
  const [sunDisabled, setSunDisabled] = useState(false);
  const [chiCangSize, setChiCangSize] = useState(0);
  const [bili, setBili] = useState(100);
  const [unit] = useState(formData?.contract.split('_')[0]);
  const [chengShu] = useState(formData?.contractInfo?.quanto_multiplier);
  const [zhiYingShouYiLv, setZhiYingShouYiLv] = useState(shouYiLv);
  const [zhiSunShouYiLv, setZhiSunShouYiLv] = useState(shouYiLv);
  const [shouXuFeiLv, setShouXuFeiLv] = useState(0); // 手续费率

  useEffect(() => {
    init();
    getFeiLv();
  }, [open]);

  // 止盈触发价
  useEffect(() => {
    const zhengFu = formData?.newSize * 1 > 0 ? 1 : -1; // 正负
    const shouYiLv = chuFa(zhiYingShouYiLv, 100) * zhengFu;
    const price = zhiYingSunTriggerPrice(shouYiLv, formData, shouXuFeiLv);
    formRef?.current?.setFieldsValue({ zhiYingPrice: price });
  }, [zhiYingShouYiLv, shouXuFeiLv]);

  // 止损触发价
  useEffect(() => {
    const zhengFu = formData?.newSize * -1 > 0 ? 1 : -1; // 正负
    const shouYiLv = chuFa(zhiSunShouYiLv, 100) * zhengFu;
    const price = zhiYingSunTriggerPrice(shouYiLv, formData, shouXuFeiLv);
    formRef?.current?.setFieldsValue({ zhiSunPrice: price });
  }, [zhiSunShouYiLv, shouXuFeiLv]);

  // 初始化设置
  function init() {
    console.log('formData: ', formData);
    const _chiCangSize = Math.abs(chengFa([formData?.size, chengShu]));
    setChiCangSize(_chiCangSize);
    setShowBFList(formData?.zhiYingSunData?.buFenCang?.list.length > 0);
    const type = 0;
    const weiTuo = !isLocal() ? 'gtc' : 'ioc';
    formRef?.current?.setFieldsValue({
      zhiYingPriceType: type,
      zhiYingWeiTuo: weiTuo,
      zhiSunPriceType: type,
      zhiSunWeiTuo: weiTuo,
      num: _chiCangSize,
    });
    if (isLocal()) {
      formRef?.current?.setFieldsValue({
        zhiYingPrice: 100000,
      });
    }
  }

  // 提交
  const submit = async () => {
    if (!showZhiYing && !showZhiSun) {
      setOpen(false);
      return;
    }
    let value = await formRef?.current?.validateFieldsReturnFormatValue();
    const { zhiYingparams, zhiSunparams } = handleZhiYingParams(value);
    // 校验数量
    if (!handleNum(zhiYingparams)) return false;
    // 处理添加逻辑
    let zhiYingRes = true;
    let zhiSunRes = true;
    if (showZhiYing) zhiYingRes = await handleZhiYingApi(zhiYingparams);
    if (showZhiSun) zhiSunRes = await handleZhiYingApi(zhiSunparams);
    if (zhiYingRes && zhiSunRes) message.success('成功');
    reload();
    setOpen(false);
  };

  // 止盈止损
  async function handleZhiYingApi(params: any) {
    const res: any = await zhiYingSunApi(params);
    if (!isSuccess(res, false)) {
      const msg = res?.msg;
      if (msg.includes('Trigger.Price must > last_price')) {
        message.error('止盈触发价必须大于最新价');
      } else {
        message.error(res.msg);
      }
      return false;
    }
    return true;
  }

  // 处理提交的参数
  function handleZhiYingParams(value: any) {
    const commonInitial: any = {
      contract: formData.contract,
      close: false, // 设置为 true 的时候执行平仓操作
      reduce_only: true,
      text: orderText,
      // size: formData?.size > 0 ? -value.num : value.num,
    };
    // 处理数量
    const _size = chuFa(value?.num, chengShu);
    commonInitial.size = chengFa([formData?.size > 0 ? -1 : 1, _size]);
    const strategy_type = 0; //  触发策略,只能用0
    const order_type =
      formData?.size > 0 ? 'plan-close-long-position' : 'plan-close-short-position';
    // 止盈
    const zhiYingparams = {
      initial: {
        ...commonInitial,
        price: value?.zhiYingWeiTuo === 'ioc' ? '0' : value?.zhiYingWeiTuoPrice + '',
        tif: value?.zhiYingWeiTuo,
      },
      trigger: {
        strategy_type, //  触发策略,只能用0
        price_type: value?.zhiYingPriceType, // 参考价格类型。 0 - 最新成交价，1 - 标记价格，2 - 指数价格
        price: value?.zhiYingPrice + '', // 价格触发时为价格，价差触发时为价差
        rule: formData?.newSize > 0 ? 1 : 2, // 价格条件类型 1 - 大于等于，2 - 小于等于；止盈为1，止损为2；注意空单取反
      },
      order_type,
    };
    // 止损
    const zhiSunparams = {
      initial: {
        ...commonInitial,
        price: value?.zhiSunWeiTuo === 'ioc' ? '0' : value?.zhiSunWeiTuoPrice + '',
        tif: value?.zhiSunWeiTuo,
      },
      trigger: {
        strategy_type, //  触发策略,只能用0
        price_type: value?.zhiSunPriceType, // 参考价格类型。 0 - 最新成交价，1 - 标记价格，2 - 指数价格
        price: value?.zhiSunPrice + '', // 价格触发时为价格，价差触发时为价差
        rule: formData?.newSize > 0 ? 2 : 1, // 价格条件类型 1 - 大于等于，2 - 小于等于；止盈为1，止损为2；注意空单取反
      },
      order_type,
    };
    return { zhiYingparams, zhiSunparams };
  }

  // 处理并检测下单数量
  function handleNum(params: any) {
    const num = Math.abs(params?.initial?.size);
    console.log('num: ', num);
    if (num < 1) {
      message.error('下单数量不能小于最小下单量');
      return false;
    }
    return true;
  }

  function onValuesChange(e: any) {
    if (e?.isZhiYing) setShowZhiYing(e?.isZhiYing?.length > 0);
    if (e?.isZhiSun) setShowZhiSun(e?.isZhiSun?.length > 0);
    if (e?.zhiYingWeiTuo) setYingDisabled(e?.zhiYingWeiTuo === 'ioc');
    if (e?.zhiSunWeiTuo) setSunDisabled(e?.zhiSunWeiTuo === 'ioc');
    if (e?.num) {
      const allSize = Math.abs(chengFa([formData?.size, chengShu]));
      const _bili = Math.ceil(chuFa(e?.num, allSize) * 100);
      setBili(_bili);
    }
  }

  function closeModal() {
    setOpen(false);
    reload();
  }

  const marks: any = { 0: '0%', 25: '25%', 50: '50%', 75: '75%', 100: '100%' };

  // 修改比例
  const changeBili = (e: any) => {
    setBili(e);
    const _chiCangSize = Math.abs(chengFa([formData?.size, chengShu, e, 0.01]));
    formRef?.current?.setFieldsValue({
      num: _chiCangSize,
    });
  };

  // 个人交易费率
  async function getFeiLv() {
    const res: any = (await feiLvApi())?.data;
    setShouXuFeiLv(+res?.futures_maker_fee);
  }

  return (
    <ModalForm
      title="部分止盈/止损"
      formRef={formRef}
      open={open}
      layout="horizontal"
      onFinish={submit}
      onOpenChange={setOpen}
      labelCol={{ span: 7 }}
      width={600}
      onValuesChange={onValuesChange}
    >
      <div className={`${styles.ZhiYingModal}`}>
        <Desc formData={formData} contractList={contractList} />
        {showBFList ? (
          <ZhiYingBFList
            formData={formData}
            setShowBFList={setShowBFList}
            closeModal={closeModal}
          />
        ) : (
          <div>
            <div className={`${styles.tmodal}`}>
              <div className={`${styles.titlerow}`}>
                <ProFormCheckbox.Group
                  name="isZhiYing"
                  options={[{ label: '止盈', value: true }]}
                />
              </div>
              <div className={`${styles.trow} ${showZhiYing && styles.trowShow}`}>
                <div className={`${styles.ttop}`}>
                  <div className={`${styles.name}`}>止盈触发价(USDT)</div>
                  <div className={`${styles.topt}`}>
                    <ProFormRadio.Group name="zhiYingPriceType" options={priceTypeOptions} />
                  </div>
                </div>
                <ProFormDigit name="zhiYingPrice" style={{ width: '100%' }} />
                <ShouYiLvSlider shouYiLv={zhiYingShouYiLv} changeShouYiLv={setZhiYingShouYiLv} />
              </div>
              <div className={`${styles.trow} ${showZhiYing && styles.trowShow}`}>
                <div className={`${styles.ttop}`}>
                  <div className={`${styles.name}`}>止盈委托价(USDT)</div>
                  <div className={`${styles.topt}`}>
                    <ProFormRadio.Group name="zhiYingWeiTuo" options={weiTuoOptions} />
                  </div>
                </div>
                <ProFormDigit
                  name="zhiYingWeiTuoPrice"
                  style={{ width: '100%' }}
                  disabled={yingDisabled}
                />
              </div>
            </div>
            <div className={`${styles.tmodal}`}>
              <div className={`${styles.titlerow}`}>
                <ProFormCheckbox.Group name="isZhiSun" options={[{ label: '止损', value: true }]} />
              </div>
              <div className={`${styles.trow} ${showZhiSun && styles.trowShow}`}>
                <div className={`${styles.ttop}`}>
                  <div className={`${styles.name}`}>止损触发价(USDT)</div>
                  <div className={`${styles.topt}`}>
                    <ProFormRadio.Group name="zhiSunPriceType" options={priceTypeOptions} />
                  </div>
                </div>
                <ProFormDigit name="zhiSunPrice" style={{ width: '100%' }} />
                <ShouYiLvSlider shouYiLv={zhiSunShouYiLv} changeShouYiLv={setZhiSunShouYiLv} />
              </div>
              <div className={`${styles.trow} ${showZhiSun && styles.trowShow}`}>
                <div className={`${styles.ttop}`}>
                  <div className={`${styles.name}`}>止损委托价(USDT)</div>
                  <div className={`${styles.topt}`}>
                    <ProFormRadio.Group name="zhiSunWeiTuo" options={weiTuoOptions} />
                  </div>
                </div>
                <ProFormDigit
                  name="zhiSunWeiTuoPrice"
                  style={{ width: '100%' }}
                  disabled={sunDisabled}
                />
              </div>
            </div>
            <div className={`${styles.tmodal}`}>
              <div className={`${styles.trow} ${styles.trowShow}`} style={{ marginTop: '10px' }}>
                <div className={`${styles.ttop}`}>
                  <div className={`${styles.name}`}>
                    数量 (
                    <span style={{ color: '#999' }}>
                      持仓数量: {chiCangSize} {unit}
                    </span>
                    )
                  </div>
                </div>
                <Tooltip
                  title={<p style={{ fontSize: '12px' }}>{`最小下单数量: ${chengShu} ${unit}`}</p>}
                >
                  <div>
                    <ProFormDigit
                      name="num"
                      style={{ width: '100%' }}
                      min={0}
                      max={chiCangSize}
                      fieldProps={{ suffix: unit }}
                      rules={[{ required: true }]}
                    />
                  </div>
                </Tooltip>
                <div>
                  <Slider value={bili} min={1} max={100} marks={marks} onChange={changeBili} />
                </div>
              </div>
            </div>
          </div>
        )}
      </div>
      <div className={`${styles.xxx}`}></div>
    </ModalForm>
  );
}
